package vertx;

import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.datagram.DatagramSocket;
import io.vertx.core.datagram.DatagramSocketOptions;
import netty.util.StartAndStop;
import test.PerformanceAnalyze;

import java.util.concurrent.CountDownLatch;

public class DatagramSocketClient extends StartAndStop {

    static PerformanceAnalyze performanceAnalyze = new PerformanceAnalyze();

    public void start() throws InterruptedException {
        String host = System.getProperty("publicAddress", "127.0.0.1");

        DatagramSocketOptions options = new DatagramSocketOptions();

        Vertx vertx = Vertx.vertx();
        DatagramSocket socket = vertx.createDatagramSocket(options);
        DatagramSocket client = vertx.createDatagramSocket(new DatagramSocketOptions());

        socket.listen(9988, "0.0.0.0", asyncResult -> {
            if (asyncResult.succeeded()) {
                socket.handler(packet -> {
                    performanceAnalyze.delay((System.nanoTime() - Long.parseLong(packet.data().toString()))/2);
                    performanceAnalyze.meter();

                    socket.send(Buffer.buffer(Long.valueOf(System.nanoTime()).toString()), 8899, host);
                });
            } else {
                System.out.println("Listen failed" + asyncResult.cause());
            }
        });

        client.send(Buffer.buffer(Long.valueOf(System.currentTimeMillis()).toString()), 8899, host);

        new CountDownLatch(1).await();
    }

    public static void main(String[] args) throws InterruptedException {


    }
}
